const mysql = require('mysql')
// npm i blueimp-md5 安装加密插件
const md5 = require('blueimp-md5')
const connection = mysql.createConnection({
    host: '1.117.61.181',
    user: 'api',
    password: 'apiapi',
    port: '3306',
    database: 'api', // 要连接的数据库名称
    connectTimeout: 5000, //连接超时
    multipleStatements: false, //是否允许一个query中包含多条sql语句
})
connection.connect()

/**
 *  保存帐号
 */
exports.save = function (user) {
    return new Promise((resolve, reject) => {
        connection.query(
            `INSERT INTO user (username,password) value ('${user.username}','${user.password}')`,
            function (err, res, fields) {
                if (err) {
                    // 发生错误的时候执行reject
                    reject(err)
                } else {
                    resolve(res)
                }
            }
        )
    })
}

/**
 *  查找一个帐号使用用户名
 */
exports.findOneByUsername = function (user) {
    return new Promise((resolve, reject) => {
        connection.query(
            `SELECT * FROM user WHERE username = '${user.username}'`,
            function (err, res, fields) {
                if (err) {
                    // 发生错误的时候执行reject
                    reject(err)
                } else {
                    resolve(res)
                }
            }
        )
    })
}
